package com.zhihaoliang.room.data.relationships

import androidx.room.*

/**
 * @author 支豪亮
 * @date 2023/1/31 15:31
 * @des 一对一关系
 */

@Entity(tableName = "user_library")
data class UserLibrary(
    @PrimaryKey val userId: Long,
    val name: String,
    val age: Int
)

@Entity
data class Library(
    @PrimaryKey val libraryId: Long,
    val userOwnerId: Long,
    val name:String
)

data class UserAndLibrary(
    @Embedded val user: UserLibrary,
    @Relation(
        parentColumn = "userId",
        entityColumn = "userOwnerId"
    )
    val library: Library
)

@Dao
interface UserLibraryDao{
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insertUser(userLibrary: List<UserLibrary>)

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insertLibrary(library:  List<Library>)

     //需要 Room 运行两次查询，因此应向该方法添加 @Transaction 注释，以确保整个操作以原子方式执行
     @Transaction
     @Query("SELECT * FROM user_library")
     suspend fun queryUsersAndLibraries(): List<UserAndLibrary>
}